/*
 * @Author: mayijun
 * @Date: 2022-05-14 09:25:52
 * @LastEditors: mayijun
 * @LastEditTime: 2022-08-12 09:50:33
 */
//指标创建
import ModifierCascader from '@/components/ModifierCascader';
import TableSearchSelect from '@/components/TableSearchSelect';
import API from '@/services';
import { EDicType, EPublishStatus } from '@/utils/constants';
import { ElCol, ElMessage, ElMessageBox, ElRow, ElTabPane, ElTabs, TabsPaneContext } from 'element-plus';
import { defineComponent, onMounted, reactive, ref } from 'vue';
import { EditPen } from '@element-plus/icons-vue';
import './index.scss';
import { useRoute, useRouter } from 'vue-router';
import { store } from '@/store';
import * as RouteNames from '@/router/consts';
import { setFieldsValue } from '@/utils/util';
import MultipleSelectDialog from '@/components/MultipleSelectDialog';
import ContentEdit from '@/views/indexManage/indexlib/indexCreate/contentEdit/index.vue';
import {
  IconExclamationCircle
} from '@arco-design/web-vue/es/icon';

const IndexCreate = defineComponent({
  name: 'IndexCreate',
  components: { ContentEdit, IconExclamationCircle },
  setup: (props, { slots, attrs, emit }) => {

    const route = useRoute();

    const router = useRouter();

    //表单ref
    let createFormRef = ref();

    /* 名称重复字段及文案 */
    const errorData = ref([]);

    //表单提交
    const indexForm: any = reactive({
      id: '',//指标id
      typeCode: 1,//指标类型的数字编号呈现。1：原子指标，2：派生指标，3：衍生指标
      enName: '',//指标英文名
      cnName: '',//指标中文名
      alias: '',//别名
      businessOwner: '',//业务负责人
      techOwner: '',//研发负责人
      department: [],//部门id，多个;分隔
      subjectId: '',//主题id
      gradeId: '',//指标等级id
      businessMeaning: '',//自定义业务含义
      unitId: '',//计量单位id
      timePeriodIds: [],//统计粒度id，多个;隔开
      description: '',//描述、备注
      authorizer: '',//授权人
      aggregationId: '',//默认聚合方式
      caliber: '',//技术口径
      dataTypeId: '',//数据类型
      dimensionIds: [],//所支持维度的id列表字符串。多个用分号(;)隔开
      source: '',//需求id
      sourceMaker: '',//提需人
      versionNo: '',//版本号
      dependMetricsId: '',//依赖的原子指标Id。仅派生指标会有此字段的值
      modifierIds: [] as any[],//修饰词id。仅派生指标需要有此字段的值，多个用分号(;)隔开
      calculationFormula: '',//计算公式。仅衍生指标会有此字段的值
      chooseMetrics: [] as any[],//选择的指标id集合。顺序用;隔开，仅衍生指标会有此字段的值
      arithmeticList: [] as any[],//衍生指标逻辑运算对象数组，仅衍生指标会有此字段的值
    });

    //校验英文名称
    const validateEnName = (rule: any, value: any, callback: any) => {
      console.log(value);
      if (value == "") {
        callback('请输入英文名称');
      } else {
        let reg = /^[a-zA-Z][a-zA-Z0-9_\-]*$/;
        if (reg.test(value)) {
          callback();
        } else {
          callback('英文名称格式必须是以字母开头，可以包含数字，_和-字符');
        }
      }
      callback();
    };

    /* 表单规则 */
    const rules: any = reactive({
      enName: [
        {
          required: true,
          validator: validateEnName,
          rigger: 'blur'
        }
      ],
      cnName: [
        {
          required: true,
          message: '请输入指标名称',
          trigger: 'blur'
        }
      ],
      businessOwner: [
        {
          required: true,
          message: '请选择业务负责人',
          trigger: 'change'
        }
      ],
      businessMeaning: [
        {
          required: true,
          message: '请输入业务含义',
          trigger: 'blur'
        }
      ],
      techOwner: [
        {
          required: true,
          message: '请选择研发负责人',
          trigger: 'change'
        }
      ],
      subjectId: [
        {
          required: true,
          message: '请选择主题层级',
          trigger: 'change'
        }
      ],
      arithmeticList: [
        {
          required: true,
          message: '请添加运算逻辑',
          trigger: 'change'
        }
      ],
      gradeId: [
        {
          required: true,
          message: '请选择指标等级',
          trigger: 'change'
        }
      ],
      timePeriodIds: [
        {
          required: true,
          message: '请选择统计粒度',
          trigger: 'change'
        }
      ],
      dependMetricsId: [
        {
          required: true,
          message: '请选择原子指标',
          trigger: 'change'
        }
      ],
      dimensionIds: [
        {
          required: true,
          message: '请选择可用维度',
          trigger: 'change'
        }
      ],
      aggregationId: [
        {
          required: true,
          message: '请选择默认聚合方式',
          trigger: 'change'
        }
      ],
      dataTypeId: [
        {
          required: true,
          message: '请选择数据类型',
          trigger: 'change'
        }
      ],
      authorizer: [
        {
          required: true,
          message: '请选择授权人',
          trigger: 'change'
        }
      ],
      versionNo: [
        {
          required: true,
          message: '请输入版本号',
          trigger: 'blur'
        }
      ],
    });

    //状态管理
    const state = reactive({
      isDisableEnName: false,//中文名称编辑
      isDisableCnName: false,//英文名称编辑
      isDisableBusinessMeaning: false,//业务含义编辑
      selectModifierList: [] as any[],//选中的修饰词对象数组
      atomItem: {} as any,//当前选择的原子指标对象
      anchorStatus: "oneId",//锚点状态值，值为对应div的id
      info: {} as any,//指标详情
      isEdits: false,//是否编辑状态
      timePeriods: [],
      dimensions: [],
    });

    /* 用户list */
    const userList: any = ref([]);

    /* 主题list */
    const subjectDeepList: any = ref([]);

    /* 修饰词list */
    const modifierList: any = ref([]);

    /* 关联部门list */
    const departmentsList: any = ref([]);

    /* 计量单位list */
    const unitList: any = ref([]);

    /* 指标等级list */
    const gradeList: any = ref([]);

    /* 默认聚合方式list */
    const aggregationList: any = ref([]);

    /* 数据类型list */
    const dataTypeList: any = ref([]);

    /* 统计粒度list */
    const statisticalPeriodList: any = ref([]);

    /* 维度list */
    const dimensionList: any = ref([]);

    /* 原子指标列表 */
    const atomList: any = ref([]);

    /* 指标选择弹出框visible */
    const dialogVisible = ref(false);

    //原子指标选择的对象
    const atomEditItem = ref({});

    //运算逻辑
    const contentEditRef = ref();

    /* 获取用户 */
    const getUser = async (name = '') => {
      try {
        const { code, data } = await API.userInfoService.getUser({ name });
        if (code === 200 && Array.isArray(data)) {
          userList.value = [...data];
        }
      } catch (error) {
        console.log(error);
      }
    };

    /* 原子指标列表 */
    const getAtomList = async (name: string) => {
      try {
        const { code, data } =
          await API.metrics.getMetricsHintSimpleList({
            content: name,
            pageNum: 1,
            pageSize: 20,
            reviewStatusCode: 5,
            types: [1],
          });
        if (code === 200 && data && Array.isArray(data.list)) {
          atomList.value = data.list;
        }
      } catch (error) {
        console.log(error);
      }
    };

    /* 主题 */
    const getSubjectDeepList = async () => {
      try {
        const { code, data } = await API.subject.getSubjectsSimpleList();
        if (code === 200 && Array.isArray(data)) {
          subjectDeepList.value = data;
        }
      } catch (error) {
        console.log(error);
      }
    };

    /* 关联部门 */
    const departmentsApi = async () => {
      try {
        const { code, data } =
          await API.dictionaryConfig.getDictionaryConfigEnumTypeByEnumType({
            enumType: EDicType.department
          });
        if (code === 200 && Array.isArray(data)) {
          departmentsList.value = data;
        }
      } catch (error) {
        console.log(error);
      }
    };

    /* 指标计量单位 */
    const getDicList = async () => {
      try {
        const { code, data } =
          await API.dictionaryConfig.getDictionaryConfigEnumTypeByEnumType({
            enumType: EDicType.unit
          });
        if (code === 200 && Array.isArray(data)) {
          unitList.value = data;
        }
      } catch (error) {
        console.log(error);
      }
    };

    /* 指标等级 */
    const getGradeList = async () => {
      try {
        const { code, data } =
          await API.dictionaryConfig.getDictionaryConfigEnumTypeByEnumType({
            enumType: EDicType.grade
          });
        if (code === 200 && Array.isArray(data)) {
          gradeList.value = data;
        }
      } catch (error) {
        console.log(error);
      }
    };

    /* 默认聚合方式 */
    const getAggregationList = async () => {
      try {
        const { code, data } =
          await API.dictionaryConfig.getDictionaryConfigEnumTypeByEnumType({
            enumType: EDicType.aggregation
          });
        if (code === 200 && Array.isArray(data)) {
          aggregationList.value = data;
        }
      } catch (error) {
        console.log(error);
      }
    };

    /* 数据类型 */
    const getDataTypeList = async () => {
      try {
        const { code, data } =
          await API.dictionaryConfig.getDictionaryConfigEnumTypeByEnumType({
            enumType: EDicType.dataType
          });
        if (code === 200 && Array.isArray(data)) {
          dataTypeList.value = data;
        }
      } catch (error) {
        console.log(error);
      }
    };

    //获取修饰词
    const getModifierList = async (name?: string) => {
      try {
        const { code, data } = await API.modifier.getModifierNameHint({
          cnName: name
        });
        if (code === 200 && Array.isArray(data)) {
          //处理修饰词树形结构
          let array: any[] = [];
          data.map((item) => {
            let child = {
              label: item.cnName,
              value: item.id,
              enName: item.enName,
              businessMeaning: item.businessMeaning,
              type: item.type,
            }
            let hasNode = array.find(obj => obj.value == item.type);
            if (hasNode) {
              hasNode.children.push(child);
            } else {
              let parent = {
                label: item.typeName,
                value: item.type,
                children: [child]
              }
              array.push(parent);
            }
          });
          modifierList.value = array;
        }
      } catch (error) {
        console.log(error);
      }
    }

    /* 统计粒度列表 */
    const getStatisticalPeriod = async (name?: string) => {
      try {
        const { code, data } = await API.timePeriod.getTimePeriodNameHint({
          cnName: name
        });
        if (code === 200 && Array.isArray(data)) {
          statisticalPeriodList.value = data;
        }
      } catch (error) {
        console.log(error);
      }
    }

    /* 获取维度下拉列表 */
    const getDimensionList = async (cnName?: string) => {
      try {
        const { code, data } = await API.dimension.getDimensionHintName({
          cnName
        });
        if (code === 200 && Array.isArray(data)) {
          dimensionList.value = data;
        }
      } catch (error) {
        console.log(error);
      }
    };

    //拼接数据，指标名称、业务含义
    const splitData = () => {
      if (indexForm.typeCode == 2) {
        let timeModifierCnName = "";
        let timeModifierEnName = "";
        let timeModifierBusinessMeaning = "";
        let businessModifierCnName = "";
        let businessModifierEnName = "";
        let businessModifierBusinessMeaning = "";
        let atomCnName = state.atomItem.cnName || "";
        let atomEnName = state.atomItem.enName || "";
        let atomBusinessMeaning = state.atomItem.businessMeaning || "";

        //时间修饰词
        let timeModifier = state.selectModifierList.find(item => item.type == 1);
        if (timeModifier) {
          timeModifierCnName = timeModifier.label || timeModifier.cnName;
          timeModifierEnName = timeModifier.enName;
          timeModifierBusinessMeaning = timeModifier.businessMeaning;
        }
        //业务修饰词
        state.selectModifierList.map(item => {
          if (item.type == 2) {
            businessModifierCnName += item.label || item.cnName;
            businessModifierEnName += "_" + item.enName;
            businessModifierBusinessMeaning += item.businessMeaning;
          }
        });

        //拼接数据   时间修饰词（0-1）+ 业务修饰词（0-多个）+ 原子指标
        indexForm.cnName = timeModifierCnName + businessModifierCnName + atomCnName;
        let enName = "";
        if (timeModifierEnName && !businessModifierEnName) {
          enName = timeModifierEnName + "_" + atomEnName;
        } else if (!timeModifierEnName && businessModifierEnName) {
          enName = businessModifierEnName.substring(1, businessModifierEnName.length) + "_" + atomEnName;
        } else if (timeModifierEnName && businessModifierEnName) {
          enName = timeModifierEnName + businessModifierEnName + "_" + atomEnName;
        } else {
          enName = atomEnName;
        }
        indexForm.enName = enName;
        indexForm.businessMeaning = timeModifierBusinessMeaning + businessModifierBusinessMeaning + atomBusinessMeaning;
      } else if (indexForm.typeCode == 3) {
        let splitBusiness = "";
        //衍生指标业务含义拼接
        indexForm.arithmeticList?.map((v: any) => {
          splitBusiness += `${v?.beforeSymbol || ''}${v?.typeCode
            ? `(${v?.businessMeaning})`
            : v?.businessMeaning || ''
            } ${v?.afterSymbol || ''} ${v?.numInput || ''}`
        });
        indexForm.businessMeaning = splitBusiness;
      }
    }

    /* 名称重复字段及文案校验 */
    const errCheck = (label: string) => {
      const errKey = errorData.value.map((v: any) => v.error_field);
      if (errKey?.includes(label)) {
        const errInfo: any = errorData.value.filter(
          (v: any) => v.error_field === label
        );
        return errInfo[0].error_msg;
      }
      return undefined;
    };

    //切换类型的时候清空数据
    const clearData = (type: any) => {

      //清空表单
      createFormRef.value.resetFields();
      //清空错误提示
      errorData.value = [];

      //清空表单
      Object.keys(indexForm).forEach((key) => {
        let type = Object.prototype.toString.call(indexForm[key]);
        if (type == "[object String]") {
          indexForm[key] = "";
        } else if (type == "[object Array]") {
          indexForm[key] = [];
        } else if (type == "[object Number]") {
          indexForm[key] = 0;//目前只有指标类型
        }
      });
      indexForm.typeCode = type;
      //需求来源赋值
      indexForm.source = route.query.source;
      //特殊处理
      indexForm.dependMetricsId = "";
      //运算逻辑
      contentEditRef.value.ruleRef.innerHTML = "";

      //清空状态
      Object.keys(state).forEach((key) => {
        let type = Object.prototype.toString.call(state[key]);
        if (type == "[object String]") {
          state[key] = "";
        } else if (type == "[object Array]") {
          state[key] = [];
        } else if (type == "[object Boolean]") {
          state[key] = false;
        }
      });
      state.anchorStatus = "oneId";

    }

    //指标类型切换
    const typeCodeChange = (tab: TabsPaneContext, event: Event) => {
      ElMessageBox.alert('如新页面中有相同字段，填写的信息将进行同步', '是否同步填写的信息?', {
        confirmButtonText: '确认同步',
        cancelButtonText: '不同步',
        showCancelButton: true,
        confirmButtonClass: 'message-box-text'
      })
        .then(async () => {
          if (tab.paneName == 1) {//原子,删除衍生和派生字段
            indexForm.dependMetricsId = "";//依赖的原子指标Id。仅派生指标会有此字段的值
            indexForm.modifierIds = [];//修饰词id。仅派生指标需要有此字段的值，多个用分号(;)隔开
            indexForm.calculationFormula = '';//计算公式。仅衍生指标会有此字段的值
            indexForm.chooseMetrics = [];//选择的指标id集合。顺序用;隔开，仅衍生指标会有此字段的值
            indexForm.arithmeticList = [];//衍生指标逻辑运算对象数组，仅衍生指标会有此字段的值
          } else if (tab.paneName == 2) {//派生，删除衍生字段
            indexForm.calculationFormula = '';//计算公式。仅衍生指标会有此字段的值
            indexForm.chooseMetrics = [];//选择的指标id集合。顺序用;隔开，仅衍生指标会有此字段的值
            indexForm.arithmeticList = [];//衍生指标逻辑运算对象数组，仅衍生指标会有此字段的值
          } else if (tab.paneName == 3) {//衍生，删除派生字段
            indexForm.dependMetricsId = "";//依赖的原子指标Id。仅派生指标会有此字段的值
            indexForm.modifierIds = [];//修饰词id。仅派生指标需要有此字段的值，多个用分号(;)隔开
          }
        })
        .catch(() => {
          //清空数据
          clearData(tab.paneName);
        })
        .finally(() => {
          //更新锚点class
          addPositionClass("oneId");
          //控制编辑项状态
          if (tab.paneName == 1) {//原子
            state.isDisableCnName = false;
            state.isDisableEnName = false;
            state.isDisableBusinessMeaning = false;
          } else if (tab.paneName == 2) {//派生
            state.isDisableCnName = true;
            state.isDisableEnName = true;
            state.isDisableBusinessMeaning = true;
          } else {//衍生
            state.isDisableCnName = false;
            state.isDisableEnName = false;
            state.isDisableBusinessMeaning = true;
          }
        });
    }

    //锚点定位
    const positionInfomation = (tab: TabsPaneContext, event: Event) => {
      let id = tab.paneName as string;
      addPositionClass(id);
    }

    //添加锚点位置的class
    const addPositionClass = (id: any) => {
      //滚动到可视区域
      let box = document.getElementById(id);
      box?.scrollIntoView();

      let timelineArray = document.getElementsByClassName("el-timeline-item");
      for (var i = 0; i < timelineArray.length; i++) {
        timelineArray[i].classList.remove("active");
      }
      let timeline = document.getElementById("timeline_" + id);
      if (timeline) {
        timeline.classList.add("active");
      }
      //锚点tab的值
      state.anchorStatus = id;
    }

    //获取基本信息的渲染对象
    const getBaseRender = (id: any) => {
      return (
        <el-timeline-item id={"timeline_" + id} placement="top">
          <div class="title" id={id}>基本信息</div>
          <ElRow gutter={18}>
            <ElCol span={6}>
              <el-form-item
                error={errCheck('cnName')}
                label="指标名称:"
                prop="cnName"
                key="cnName"
              >
                <el-input
                  size="large"
                  disabled={
                    state.info.reviewStatus == 3 ||
                    state.isDisableCnName
                  }
                  v-model={indexForm.cnName}
                  clearable
                  placeholder="请输入"
                ></el-input>
                {state.isDisableCnName && (
                  <el-button type="text" icon={EditPen} class="edit-btn" onClick={() => {
                    state.isDisableCnName = false;
                  }}></el-button>
                )}
              </el-form-item>
            </ElCol>
            <ElCol span={6}>
              <el-form-item
                error={errCheck('enName')}
                label="英文名称:"
                prop="enName"
                key="enName"
              >
                <el-input
                  size="large"
                  disabled={
                    state.info.reviewStatus == 3 ||
                    state.isDisableEnName
                  }
                  v-model={indexForm.enName}
                  placeholder="请输入"
                  clearable
                ></el-input>
                {state.isDisableEnName && (
                  <el-button type="text" icon={EditPen} class="edit-btn" onClick={() => {
                    state.isDisableEnName = false;
                  }}></el-button>
                )}
              </el-form-item>
            </ElCol>
            <ElCol span={6}>
              <el-form-item label="指标等级:" prop="gradeId" key="gradeId">
                <TableSearchSelect
                  list={gradeList.value}
                  v-model={[indexForm.gradeId, 'modelVal']}
                />
              </el-form-item>
            </ElCol>
            <ElCol span={6}>
              <el-form-item label="指标别名:">
                <el-input
                  size="large"
                  v-model={indexForm.alias}
                  clearable
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </ElCol>
          </ElRow>
          <ElRow gutter={18}>
            <ElCol span={6}>
              <el-form-item label="计量单位:" prop="unitId" key="unitId">
                <TableSearchSelect
                  list={unitList.value}
                  v-model={[indexForm.unitId, 'modelVal']}
                />
              </el-form-item>
            </ElCol>
            {state.isEdits && (
              <ElCol span={6}>
                <el-form-item label="指标ID:">
                  <el-input
                    size="large"
                    disabled={true}
                    v-model={indexForm.id}
                  ></el-input>
                </el-form-item>
              </ElCol>
            )}
          </ElRow>
          {state.isEdits && (
            <ElRow gutter={18}>
              <ElCol span={6}>
                <el-form-item label="创建人:">
                  <el-input
                    size="large"
                    disabled={true}
                    v-model={state.info.createBy}
                  ></el-input>
                </el-form-item>
              </ElCol>
              <ElCol span={6}>
                <el-form-item label="创建时间:">
                  <el-input
                    size="large"
                    disabled={true}
                    v-model={state.info.createTime}
                  ></el-input>
                </el-form-item>
              </ElCol>
            </ElRow>
          )}
          <ElRow gutter={18}>
            <ElCol span={9}>
              <el-form-item label="业务含义:" prop="businessMeaning" key="businessMeaning" class="business-meaning">
                <el-input
                  type="textarea"
                  disabled={state.isDisableBusinessMeaning && indexForm.typeCode == 2}
                  v-model={indexForm.businessMeaning}
                  //@ts-ignore
                  rows={4}
                  max={200}
                  placeholder="请输入"
                />
                {indexForm.typeCode == 2 && state.isDisableBusinessMeaning && (
                  <el-button type="text" icon={EditPen} class="edit-btn" onClick={() => {
                    state.isDisableBusinessMeaning = false;
                  }}></el-button>
                )}
              </el-form-item>
            </ElCol>
          </ElRow>
        </el-timeline-item>
      )
    }

    //获取业务信息渲染对象
    const getBusinessRender = (id: any) => {
      return (
        <el-timeline-item id={"timeline_" + id} placement="top">
          <div class="title" id={id}>业务信息</div>
          <ElRow gutter={18}>
            <ElCol span={6}>
              <el-form-item label="业务负责人:" prop="businessOwner" key="businessOwner">
                <TableSearchSelect
                  isRemote={true}
                  labelJoin={true}
                  list={userList.value}
                  v-model={[indexForm.businessOwner, 'modelVal']}
                  remoteMethod={(name: string) => getUser(name)}
                  placeholder="请输入"
                />
              </el-form-item>
            </ElCol>
            <ElCol span={6}>
              <el-form-item label="关联部门:" prop="department" key="department">
                <MultipleSelectDialog
                  v-model={[indexForm.department, 'modelVal']}
                  dataList={departmentsList.value}
                ></MultipleSelectDialog>
              </el-form-item>
            </ElCol>
          </ElRow>
          <ElRow gutter={18}>
            <ElCol span={12}>
              <el-form-item label="备注:" prop="description" key="description">
                <el-input
                  v-model={indexForm.description}
                  rows={4}
                  type="textarea"
                  placeholder="请输入"
                />
              </el-form-item>
            </ElCol>
          </ElRow>
        </el-timeline-item>
      )
    }

    //底部按钮区域渲染对象
    const footerRender = () => {

      if (state.info && state.info.reviewStatus) {
        if (state.info.reviewStatus == 1) {
          return (
            <>
              <el-button onClick={toRouter}>取消</el-button>
              <el-button onClick={() => submit()}>
                更新
              </el-button>
              <el-button type="primary" onClick={() => submit(5)}>
                发布
              </el-button>
            </>
          );
        }
        return (
          <>
            <el-button onClick={toRouter}>取消</el-button>
            <el-button type="primary" onClick={() => submit()}>
              更新
            </el-button>
          </>
        );
      }
      return (
        <>
          <el-button onClick={() => { clearData(indexForm.typeCode) }}>
            重置
          </el-button>
          <el-button onClick={() => submit(1)}>
            暂存
          </el-button>
          <el-button type="primary" onClick={() => submit(5)}>
            提交
          </el-button>
        </>
      );
    };

    const submit = async (status?: Number) => {
      /**
       * status
       * 空 更新
       * 1 暂存
       * 2 新建提交审核
       * 3 编辑提交审核
       */
      createFormRef.value.validate(async (bol: boolean) => {
        if (!bol) return;

        const { department, arithmeticList, timePeriodIds, modifierIds, dimensionIds } = indexForm;

        let meticList = arithmeticList.filter((item: any) => item != undefined);
        const params = {
          ...indexForm,
          department: department.join(';'), //关联部门
          timePeriodIds: timePeriodIds.join(';'), //统计粒度
          dimensionIds: dimensionIds.join(';'),//可用维度
          modifierIds: modifierIdsFormat(modifierIds), //修饰词
          chooseMetrics: arithmeticFormat(meticList), //指标id集合
          arithmeticList: meticList
        };
        if (indexForm.typeCode == 3) {
          let text = contentEditRef.value.ruleRef.innerText;
          params.calculationFormula = text.replace(/[\u200b]/g, ''); //计算公式
        }
        //暂存是1 ,提交2
        if (status == 1) {
          params.opType = 1;
        } else if (status == 5) {
          params.opType = 2;
        }

        try {
          if (!state.isEdits) {
            const { code, data }: any = await API.metrics.postMetrics({
              ...params
            });
            if (code === 200) {
              ElMessage.success(`${status == 1 ? '暂存' : '提交'}成功`);
              clearData(indexForm.typeCode);
            } else {
              errorData.value = data;
            }
          } else {
            if (status == 5) {
              params.opType = 2;
            }
            params.id = state.info.id;
            const { code, data }: any = await API.metrics.putMetrics({
              ...params
            });
            if (code === 200) {
              ElMessage.success(`${status == 5 ? '发布' : '更新'}成功`);
              toRouter();
            } else {
              errorData.value = data;
            }
          }
        } catch (error) {
          console.warn(error);
        }
      });
    };

    //修饰词格式处理
    const modifierIdsFormat = (data: any) => {
      if (data.length == 0) {
        return '';
      }
      const ids = data.map((obj: any) => {
        return obj[1];
      });
      return ids.join(';');
    };

    /* 运算逻辑处理数据格式 */
    const arithmeticFormat = (data: any) => {
      const chooseMetrics = data
        ?.map((v: any) => `${v.selectIndexId}.${v.CombineEnumVal}`)
        .join(';');
      return chooseMetrics;
    };

    //跳转到指标元信息
    const toRouter = () => {
      router.push({
        name: RouteNames.ROUTE_ATOMINDEXMANAGE
      });
    }

    /* 指标详情 */
    const getMetricsInfo = async (id: any) => {
      try {
        const { code, data }: any = await API.metrics.getMetricsById({ id });
        if (code === 200 && data) {
          state.info = data;

          //编辑赋值处理

          //通过key值赋值
          setFieldsValue(indexForm, data);

          //原子指标下拉处理
          if (data.dependMetricsId) {
            //由于原子指标下拉是分页查找，如果不存在无法反显，如果没找到把详情里的数据放入下拉
            let atomItem = atomList.value.find((item: any) => item.id == data.dependMetricsId);
            if (atomItem == undefined) {
              atomList.value.push(data.dependMetrics);
            }
          }

          //修饰词处理
          if (data.modifiers) {
            indexForm.modifierIds = data.modifiers.map((item: any) => {
              return [item.type, item.id];
            });
          }
          indexForm.businessMeaning = data.businessMeaning;
          indexForm.unitId = data.unitId ? String(data.unitId) : '';
          indexForm.subjectId = String(data.subjectId);
          indexForm.typeCode = data.metricsType;
          indexForm.gradeId = String(data.gradeId);
          indexForm.aggregationId = String(data.aggregationId);
          indexForm.dataTypeId = String(data.dataTypeId);
          indexForm.department = data.departments.map((item: any) => String(item.id));
          indexForm.timePeriodIds = data.timePeriodIds.split(";").filter((item: any) => {
            if (item) {
              return item;
            }
          }).map(Number);
          state.timePeriods = data.timePeriods;

          //可用维度
          indexForm.dimensionIds = data.dimensions.map((item: any) => Number(item.id));
          state.dimensions = data.dimensions;

          if (data.arithmeticList?.length > 0) {
            indexForm.arithmeticList = data.arithmeticList;
          }

          if (data.metricsType == 2) {
            state.isDisableCnName = true;
            state.isDisableEnName = true;
            state.isDisableBusinessMeaning = true;
          } else if (data.metricsType == 3) {
            state.isDisableBusinessMeaning = true;
          }
          //拼接数据
          state.atomItem = data.dependMetrics;
          state.selectModifierList = data.modifiers;
        }
      } catch (error) {
        console.log(error);
      }
    };

    onMounted(() => {
      departmentsApi();
      getSubjectDeepList();
      getModifierList();
      getDicList();
      getGradeList();
      getAggregationList();
      getDataTypeList();
      getStatisticalPeriod();
      getDimensionList();
      getUser();
      getAtomList('');
      addPositionClass("oneId");
      //需求来源赋值
      indexForm.source = route.query.source;
      //查询指标详情
      if (route.query.id) {
        state.isEdits = true;
        getMetricsInfo(route.query.id);
        store.commit('breadcrumb/setShowReturn', true); //是否显示返回
        // 返回对象及返回动作
        store.commit('breadcrumb/setBackParams', {
          name: RouteNames.ROUTE_ATOMINDEXMANAGE
        });
      }
    });

    return () => {

      return (
        <div class="index-create">
          {!state.isEdits && (
            <ElTabs class="tab-type" v-model={indexForm.typeCode} onTab-click={typeCodeChange}>
              <ElTabPane label="原子指标" name={1}></ElTabPane>
              <ElTabPane label="派生指标" name={2}></ElTabPane>
              <ElTabPane label="衍生指标" name={3}></ElTabPane>
            </ElTabs>
          )}
          <el-form
            ref={createFormRef}
            model={indexForm}
            rules={rules}
            label-position={'top'}
          >
            <div class={["layout-base", state.isEdits ? "layout-edit" : ""]}>
              <div class="timeline-left">
                <el-timeline>
                  {/* 原子指标one */}
                  {indexForm.typeCode == 1 && getBaseRender("oneId")}
                  {/* 派生指标one */}
                  {indexForm.typeCode == 2 && (
                    <el-timeline-item id="timeline_oneId" placement="top">
                      <div class="title" id="oneId">技术信息</div>
                      <ElRow gutter={18}>
                        <ElCol span={6}>
                          <el-form-item label="原子指标:" prop="dependMetricsId" key="dependMetricsId">
                            <TableSearchSelect
                              isRemote={true}
                              fieldLabel="cnName"
                              fieldValue="id"
                              editItem={atomEditItem.value}
                              v-model={[indexForm.dependMetricsId, 'modelVal']}
                              list={atomList.value}
                              remoteMethod={(name: string) => getAtomList(name)}
                              selectConfig={{
                                onChange: (v: any) => {
                                  //当前选中的原子指标对象
                                  state.atomItem = atomList.value.find(
                                    (j: any) => j.id === v
                                  );
                                  //创建时默认主题
                                  if (!state.isEdits) {
                                    indexForm.subjectId = String(state.atomItem.subjectId);
                                  }
                                  //拼接数据
                                  splitData();
                                  //清空四个校验信息
                                  createFormRef.value.clearValidate("cnName");
                                  createFormRef.value.clearValidate("enName");
                                  createFormRef.value.clearValidate("subjectId");
                                  createFormRef.value.clearValidate("businessMeaning");
                                }
                              }}
                            />
                          </el-form-item>
                        </ElCol>
                        <ElCol span={6}>
                          <el-form-item label="修饰词:" prop="modifierIds" key="modifierIds">
                            <ModifierCascader
                              list={modifierList.value}
                              v-model={[indexForm.modifierIds, 'modelVal']}
                              onChange={(v: any[]) => {
                                //排序数组，时间修饰词在第一个，业务修饰词按照选择的顺序排列
                                let sortArray = [];
                                //找到时间修饰词，放入数组,在第一个位置添加
                                for (var i = v.length - 1; i >= 0; i--) {
                                  if (v[i][0] == 1) {
                                    sortArray.unshift(v[i]);
                                    break;
                                  }
                                }

                                let filterArray = v.filter(item => {
                                  if (item[0] != 1) {
                                    return item;
                                  }
                                });
                                sortArray = sortArray.concat(filterArray);
                                //先清空在赋值
                                state.selectModifierList = [];
                                sortArray.map((modifier: any) => {
                                  let parentNode = modifierList.value.find((obj: any) => obj.value == modifier[0]);
                                  let childNode = parentNode.children.find((obj: any) => obj.value == modifier[1]);
                                  state.selectModifierList.push(childNode);
                                });
                                indexForm.modifierIds = sortArray;
                                //拼接数据
                                splitData();
                              }}
                            ></ModifierCascader>
                          </el-form-item>
                        </ElCol>
                        <ElCol span={6}>
                          <el-form-item label="研发负责人:" prop="techOwner" key="techOwner">
                            <TableSearchSelect
                              isRemote={true}
                              list={userList.value}
                              v-model={[indexForm.techOwner, 'modelVal']}
                              remoteMethod={(name: string) => getUser(name)}
                              placeholder="请输入"
                            />
                          </el-form-item>
                        </ElCol>
                        <ElCol span={6}>
                          <el-form-item label="统计粒度:" prop="timePeriodIds" key="timePeriodIds">
                            <TableSearchSelect
                              list={statisticalPeriodList.value}
                              v-model={[indexForm.timePeriodIds, 'modelVal']}
                              isRemote={true}
                              remoteMethod={(name: string) => getStatisticalPeriod(name)}
                              fieldLabel="cnName"
                              fieldValue="id"
                              mergeArr={state.timePeriods}
                              selectConfig={{
                                onVisibleChange: (val: any) => {
                                  if (!val) {
                                    getStatisticalPeriod();
                                  }
                                },
                                disabled:
                                  state.info.reviewStatus == 3 ||
                                  state.isEdits
                                ,
                                multiple: true,
                                collapseTags: true,
                                collapseTagsTooltip: true,
                              }}
                            />
                          </el-form-item>
                        </ElCol>
                      </ElRow>
                      <ElRow gutter={18}>
                        <ElCol span={6}>
                          <el-form-item label="默认聚合方式:" prop="aggregationId" key="aggregationId">
                            <TableSearchSelect
                              list={aggregationList.value}
                              v-model={[indexForm.aggregationId, 'modelVal']}
                            />
                          </el-form-item>
                        </ElCol>
                        <ElCol span={6}>
                          <el-form-item label="主题层级:" prop="subjectId" key="subjectId">
                            <el-cascader
                              size="large"
                              v-model={indexForm.subjectId}
                              options={subjectDeepList.value}
                              append-to-body={false}
                              placeholder="请选择"
                              onChange={(v: any) => {
                                indexForm.subjectId = v?.length ? v[v?.length - 1] : '';
                              }}
                            ></el-cascader>
                          </el-form-item>
                        </ElCol>
                        <ElCol span={6}>
                          <el-form-item label="数据类型:" prop="dataTypeId" key="dataTypeId">
                            <TableSearchSelect
                              list={dataTypeList.value}
                              v-model={[indexForm.dataTypeId, 'modelVal']}
                            />
                          </el-form-item>
                        </ElCol>
                        <ElCol span={6}>
                          <el-form-item label="可用维度:" prop="dimensionIds" key="dimensionIds">
                          <TableSearchSelect
                              list={dimensionList.value}
                              v-model={[indexForm.dimensionIds, 'modelVal']}
                              isRemote={true}
                              remoteMethod={(name: string) => getDimensionList(name)}
                              fieldLabel="cnName"
                              fieldValue="id"
                              mergeArr={state.dimensions}
                              selectConfig={{
                                onVisibleChange: (val: any) => {
                                  if (!val) {
                                    getDimensionList();
                                  }
                                },
                                disabled:
                                  state.info.reviewStatus == 3 ||
                                  state.isEdits
                                ,
                                multiple: true,
                                collapseTags: true,
                                collapseTagsTooltip: true,
                              }}
                            />
                          </el-form-item>
                        </ElCol>
                      </ElRow>
                      {state.isEdits && (
                        <ElRow gutter={18}>
                          <ElCol span={6}>
                            <el-form-item label="指标类型:">
                              <el-input
                                size="large"
                                disabled={true}
                                v-model={state.info.metricsTypeName}
                              ></el-input>
                            </el-form-item>
                          </ElCol>
                        </ElRow>
                      )}
                      <ElRow gutter={18}>
                        <ElCol span={15}>
                          <el-form-item label="技术口径:" prop="caliber" key="caliber">
                            <el-input
                              v-model={indexForm.caliber}
                              rows={4}
                              type="textarea"
                              placeholder="请输入"
                            />
                          </el-form-item>
                        </ElCol>
                      </ElRow>
                    </el-timeline-item>
                  )}
                  {/* 衍生指标one */}
                  {indexForm.typeCode == 3 && getBaseRender("oneId")}
                  {/* 原子指标two */}
                  {indexForm.typeCode == 1 && getBusinessRender("twoId")}
                  {/* 派生指标two */}
                  {indexForm.typeCode == 2 && getBaseRender("twoId")}
                  {/* 衍生指标two */}
                  {indexForm.typeCode == 3 && getBusinessRender("twoId")}
                  {/* 原子指标three */}
                  {indexForm.typeCode == 1 && (
                    <el-timeline-item id="timeline_threeId" placement="top">
                      <div class="title" id="threeId">技术信息</div>
                      <ElRow gutter={18}>
                        <ElCol span={6}>
                          <el-form-item label="研发负责人:" prop="techOwner" key="techOwner">
                            <TableSearchSelect
                              isRemote={true}
                              list={userList.value}
                              v-model={[indexForm.techOwner, 'modelVal']}
                              remoteMethod={(name: string) => getUser(name)}
                              placeholder="请输入"
                            />
                          </el-form-item>
                        </ElCol>
                        <ElCol span={6}>
                          <el-form-item label="统计粒度:" prop="timePeriodIds" key="timePeriodIds">
                            <TableSearchSelect
                              list={statisticalPeriodList.value}
                              v-model={[indexForm.timePeriodIds, 'modelVal']}
                              isRemote={true}
                              remoteMethod={(name: string) => getStatisticalPeriod(name)}
                              fieldLabel="cnName"
                              fieldValue="id"
                              mergeArr={state.timePeriods}
                              selectConfig={{
                                onVisibleChange: (val: any) => {
                                  if (!val) {
                                    getStatisticalPeriod();
                                  }
                                },
                                disabled:
                                  state.info.reviewStatus == 3 ||
                                  state.isEdits
                                ,
                                multiple: true,
                                collapseTags: true,
                                collapseTagsTooltip: true,
                              }}
                            />
                          </el-form-item>
                        </ElCol>
                        <ElCol span={6}>
                          <el-form-item label="主题层级:" prop="subjectId" key="subjectId">
                            <el-cascader
                              size="large"
                              v-model={indexForm.subjectId}
                              options={subjectDeepList.value}
                              append-to-body={false}
                              placeholder="请选择"
                              onChange={(v: any) => {
                                indexForm.subjectId = v?.length ? v[v?.length - 1] : '';
                              }}
                            ></el-cascader>
                          </el-form-item>
                        </ElCol>
                        <ElCol span={6}>
                          <el-form-item label="默认聚合方式:" prop="aggregationId" key="aggregationId">
                            <TableSearchSelect
                              list={aggregationList.value}
                              v-model={[indexForm.aggregationId, 'modelVal']}
                            />
                          </el-form-item>
                        </ElCol>
                      </ElRow>
                      <ElRow gutter={18}>
                        <ElCol span={6}>
                          <el-form-item label="数据类型:" prop="dataTypeId" key="dataTypeId">
                            <TableSearchSelect
                              list={dataTypeList.value}
                              v-model={[indexForm.dataTypeId, 'modelVal']}
                            />
                          </el-form-item>
                        </ElCol>
                        <ElCol span={6}>
                          <el-form-item label="可用维度:" prop="dimensionIds" key="dimensionIds">
                          <TableSearchSelect
                              list={dimensionList.value}
                              v-model={[indexForm.dimensionIds, 'modelVal']}
                              isRemote={true}
                              remoteMethod={(name: string) => getDimensionList(name)}
                              fieldLabel="cnName"
                              fieldValue="id"
                              mergeArr={state.dimensions}
                              selectConfig={{
                                onVisibleChange: (val: any) => {
                                  if (!val) {
                                    getDimensionList();
                                  }
                                },
                                disabled:
                                  state.info.reviewStatus == 3 ||
                                  state.isEdits
                                ,
                                multiple: true,
                                collapseTags: true,
                                collapseTagsTooltip: true,
                              }}
                            />
                          </el-form-item>
                        </ElCol>
                        {state.isEdits && (
                          <ElCol span={6}>
                            <el-form-item label="指标类型:">
                              <el-input
                                size="large"
                                disabled={true}
                                v-model={state.info.metricsTypeName}
                              ></el-input>
                            </el-form-item>
                          </ElCol>
                        )}
                      </ElRow>
                      <ElRow gutter={18}>
                        <ElCol span={15}>
                          <el-form-item label="技术口径:" prop="caliber" key="caliber">
                            <el-input
                              v-model={indexForm.caliber}
                              rows={4}
                              type="textarea"
                              placeholder="请输入"
                            />
                          </el-form-item>
                        </ElCol>
                      </ElRow>
                    </el-timeline-item>
                  )}
                  {/* 派生指标three */}
                  {indexForm.typeCode == 2 && getBusinessRender("threeId")}
                  {/* 衍生指标three */}
                  {indexForm.typeCode == 3 && (
                    <el-timeline-item id="timeline_oneId" placement="top">
                      <div class="title" id="threeId">技术信息</div>
                      <ElRow gutter={18}>
                        <ElCol span={6}>
                          <el-form-item label="研发负责人:" prop="techOwner" key="techOwner">
                            <TableSearchSelect
                              isRemote={true}
                              list={userList.value}
                              v-model={[indexForm.techOwner, 'modelVal']}
                              remoteMethod={(name: string) => getUser(name)}
                              placeholder="请输入"
                            />
                          </el-form-item>
                        </ElCol>
                        <ElCol span={6}>
                          <el-form-item label="统计粒度:" prop="timePeriodIds" key="timePeriodIds">
                            <TableSearchSelect
                              list={statisticalPeriodList.value}
                              v-model={[indexForm.timePeriodIds, 'modelVal']}
                              isRemote={true}
                              remoteMethod={(name: string) => getStatisticalPeriod(name)}
                              fieldLabel="cnName"
                              fieldValue="id"
                              mergeArr={state.timePeriods}
                              selectConfig={{
                                onVisibleChange: (val: any) => {
                                  if (!val) {
                                    getStatisticalPeriod();
                                  }
                                },
                                disabled:
                                  state.info.reviewStatus == 3 ||
                                  state.isEdits
                                ,
                                multiple: true,
                                collapseTags: true,
                                collapseTagsTooltip: true,
                              }}
                            />
                          </el-form-item>
                        </ElCol>
                        <ElCol span={6}>
                          <el-form-item label="主题层级:" prop="subjectId" key="subjectId">
                            <el-cascader
                              size="large"
                              v-model={indexForm.subjectId}
                              options={subjectDeepList.value}
                              append-to-body={false}
                              placeholder="请选择"
                              onChange={(v: any) => {
                                indexForm.subjectId = v?.length ? v[v?.length - 1] : '';
                              }}
                            ></el-cascader>
                          </el-form-item>
                        </ElCol>
                        <ElCol span={6}>
                          <el-form-item label="默认聚合方式:" prop="aggregationId" key="aggregationId">
                            <TableSearchSelect
                              list={aggregationList.value}
                              v-model={[indexForm.aggregationId, 'modelVal']}
                            />
                          </el-form-item>
                        </ElCol>
                      </ElRow>
                      <ElRow gutter={18}>
                        <ElCol span={6}>
                          <el-form-item label="数据类型:" prop="dataTypeId" key="dataTypeId">
                            <TableSearchSelect
                              list={dataTypeList.value}
                              v-model={[indexForm.dataTypeId, 'modelVal']}
                            />
                          </el-form-item>
                        </ElCol>
                        <ElCol span={6}>
                          <el-form-item label="可用维度:" prop="dimensionIds" key="dimensionIds">
                            <TableSearchSelect
                              list={dimensionList.value}
                              v-model={[indexForm.dimensionIds, 'modelVal']}
                              isRemote={true}
                              remoteMethod={(name: string) => getDimensionList(name)}
                              fieldLabel="cnName"
                              fieldValue="id"
                              mergeArr={state.dimensions}
                              selectConfig={{
                                onVisibleChange: (val: any) => {
                                  if (!val) {
                                    getDimensionList();
                                  }
                                },
                                disabled:
                                  state.info.reviewStatus == 3 ||
                                  state.isEdits
                                ,
                                multiple: true,
                                collapseTags: true,
                                collapseTagsTooltip: true,
                              }}
                            />
                          </el-form-item>
                        </ElCol>
                        {state.isEdits && (
                          <ElCol span={6}>
                            <el-form-item label="指标类型:">
                              <el-input
                                size="large"
                                disabled={true}
                                v-model={state.info.metricsTypeName}
                              ></el-input>
                            </el-form-item>
                          </ElCol>
                        )}
                      </ElRow>
                      <ElRow gutter={18}>
                        <ElCol span={15}>
                          <el-form-item prop="arithmeticList" key="arithmeticList" label="运算逻辑:">
                            <content-edit calculationFormula={indexForm.calculationFormula} ref={contentEditRef} arithmeticList={indexForm.arithmeticList}></content-edit>
                            <a-popover title="填写示例" content-class="example-popover" position="top" v-slots={
                              {
                                content: ({ node, data }: any) => (
                                  <div class="arithmetic-example">
                                    <div>
                                      <span class="text">近3天华东地区</span>
                                      <span class="active">日用品销售额</span>
                                      <span class="text">/华东地区</span>
                                      <span class="active">商品销售额</span>
                                    </div>
                                    <div>
                                      <span class="text">华东地区不包括苏州，近3天是从当天开始算 | </span>
                                      <span class="info">输入“#”</span>
                                    </div>
                                    <div class="btn-foot">
                                      <span class="info">可插入指标</span>
                                      <span class="btn">&lt;/&gt;插入指标</span>
                                    </div>
                                  </div>
                                )
                              }
                            }>
                              <a-button type="text" class="info-btn">
                                <icon-exclamation-circle />
                              </a-button>
                            </a-popover>
                          </el-form-item>
                        </ElCol>
                      </ElRow>
                      <ElRow gutter={18}>
                        <ElCol span={15}>
                          <el-form-item label="技术口径:" prop="caliber" key="caliber">
                            <el-input
                              v-model={indexForm.caliber}
                              rows={4}
                              type="textarea"
                              placeholder="请输入"
                            />
                          </el-form-item>
                        </ElCol>
                      </ElRow>
                    </el-timeline-item>
                  )}
                  {/* 公共指标four */}
                  <el-timeline-item id="timeline_fourId" placement="top">
                    <div class="title" id="fourId">管理信息</div>
                    <ElRow gutter={18}>
                      <ElCol span={6}>
                        <el-form-item label="版本号:" prop="versionNo" key="versionNo">
                          <el-input
                            size="large"
                            v-model={indexForm.versionNo}
                            clearable
                            placeholder="请输入"
                          ></el-input>
                        </el-form-item>
                      </ElCol>
                      <ElCol span={6}>
                        <el-form-item label="授权人:" prop="authorizer" key="authorizer">
                          <TableSearchSelect
                            isRemote={true}
                            list={userList.value}
                            v-model={[indexForm.authorizer, 'modelVal']}
                            remoteMethod={(name: string) => getUser(name)}
                            placeholder="请输入"
                          />
                        </el-form-item>
                      </ElCol>
                      {state.isEdits && (
                        <>
                          <ElCol span={6}>
                            <el-form-item label="更新人:">
                              <el-input
                                size="large"
                                disabled={true}
                                v-model={state.info.updateBy}
                              ></el-input>
                            </el-form-item>
                          </ElCol>
                          <ElCol span={6}>
                            <el-form-item label="更新时间:">
                              <el-input
                                size="large"
                                disabled={true}
                                v-model={state.info.updateTime}
                              ></el-input>
                            </el-form-item>
                          </ElCol>
                        </>
                      )}
                    </ElRow>
                  </el-timeline-item>
                </el-timeline>
              </div>
              <div class="tab-right">
                <ElTabs v-model={state.anchorStatus} tabPosition='left' onTab-click={positionInfomation} class="right-position">
                  <ElTabPane label={indexForm.typeCode == 1 || indexForm.typeCode == 3 ? "基本信息" : "技术信息"} name="oneId"></ElTabPane>
                  <ElTabPane label={indexForm.typeCode == 1 || indexForm.typeCode == 3 ? "业务信息" : "基本信息"} name="twoId"></ElTabPane>
                  <ElTabPane label={indexForm.typeCode == 1 || indexForm.typeCode == 3 ? "技术信息" : "业务信息"} name="threeId"></ElTabPane>
                  <ElTabPane label="管理信息" name="fourId"></ElTabPane>
                </ElTabs>
              </div>
            </div>
            <div class="footer">{footerRender()}</div>
          </el-form>
        </div >
      );
    };
  }
});

export default IndexCreate;
